<?php

namespace app\admin\model;

use think\Model;

class AuthRule extends Model
{
    public function authRuleTree(){
        $authRuleRes=$this->order('sort desc')->select();
        return $this->sort($authRuleRes);
    }

    public function sort($data,$pid=0){
        static $arr=array();
        foreach ($data as $k => $v) {
            if($v['pid']==$pid){
                $v['dataId']=$this->getParentId($v['id']);
                $arr[]=$v;
                $this->sort($data,$v['id']);
            }
        }
        return $arr;
    }

    public function getChildrenId($authRuleId){
        $AuthRuleRes=$this->select();
        return $this->_getChildrenId($AuthRuleRes,$authRuleId);
    }

    public function _getChildrenId($AuthRuleRes,$authRuleId){
        static $arr=array();
        foreach ($AuthRuleRes as $k => $v) {
            if($v['pid'] == $authRuleId){
                $arr[]=$v['id'];
                $this->_getChildrenId($AuthRuleRes,$v['id']);
            }
        }

        return $arr;
    }


    public function getParentId($authRuleId){
        $AuthRuleRes=$this->select();
        return $this->_getParentId($AuthRuleRes,$authRuleId,True);
    }

    public function _getParentId($AuthRuleRes,$authRuleId,$clear=False){
        static $arr=array();
        if($clear){
            $arr=array();
        }
        foreach ($AuthRuleRes as $k => $v) {
            if($v['id'] == $authRuleId){
                $arr[]=$v['id'];
                $this->_getParentId($AuthRuleRes,$v['pid'],False);
            }
        }
        asort($arr);
        $arrStr=implode('-', $arr);
        return $arrStr;
    }
}
